$(document).ready(function () {
    //点击刷新验证码
    $('body').on('click', '.captcha-img img', function (e) {
        var img_src = $(this).attr('src');
        var curr_date = new Date();
        var curr_time =
            '' +
            curr_date.getFullYear() +
            curr_date.getMonth() +
            curr_date.getDate() +
            curr_date.getHours() +
            curr_date.getMinutes() +
            curr_date.getSeconds();
        var new_src = img_src.split('?', 2)[0] + '?' + curr_time;
        $(this).attr('src', new_src);
        $('input[name=captcha]').val('');
        return false;
    });

    /*-------------------------------------------------------------------------------------
     *               Ajax 相关操作
     *-----------------------------------------------------------------------------------*/

    $.doAjax = function (obj, type) {
        var ele = $(obj);
        var url;
        var data = {};
        var request_type = type.toUpperCase();
        var post_target_form;
        var callback = ele.attr('ajax-callback');
        if (
            (request_type == 'POST' || request_type == 'PUT' || request_type == 'PATCH')
            &&
            (post_target_form = ele.attr('target-form'))
        ) {
            url = $('#' + post_target_form).attr('action');
            data = $('#' + post_target_form).serializeArray();
        } else {
            url = ele.attr('ajax-url') || ele.attr('href');
        }
        if (!url) {
            layer.msg('未指定提交目标地址！', {
                offset: '150px',
                shade: [0.2, '#666'],
                shadeClose: true,
                icon: 2,
                time: 2000
            });
            return false;
        }
        if (ele.attr('ajax-data')) {
            var attr_data = jQuery.parseJSON(ele.attr('ajax-data'));
            $.extend(true, data, attr_data);
        }
        if (
            request_type == 'POST' ||
            request_type == 'PUT' ||
            request_type == 'PATCH' ||
            request_type == 'DELETE'
        ) {
            var data_method = [
                {
                    "name": "_token",
                    "value": $('input[name=_token]').val() ? $('input[name=_token]').val() : $('meta[name=csrf-token]').attr('content')
                }
            ];
            if (request_type != 'POST') {
                data_method = $.merge([{
                    "name": "_method",
                    "value": request_type
                }], data_method);
            }
            data = $.merge(data_method, data)
        }
        if (ele.hasClass('confirm')) {
            var attr_confirm_tip = ele.attr('confirm-tip');
            var confirm_tip = attr_confirm_tip
                ? attr_confirm_tip
                : '确定要执行该操作吗？';

            layer.confirm(confirm_tip, {
                time: 0, //不自动关闭
                title: false,
                btn: ['确定', '取消'],
                icon: 3,
                offset: '150px',
                shade: [0.2, '#666'],
                yes: function (index) {
                    layer.close(index);
                    ele.prop('disabled', true);
                    $.ajaxSend(ele, type, url, data, callback);
                    return false;
                },
                cancel: function (index) {
                    layer.close(index);
                    return false;
                }
            });
        } else {
            ele.prop('disabled', true);
            $.ajaxSend(ele, type, url, data, callback);
        }
        return false;
    };

    $.ajaxSend = function (ele, type, url, data, callback) {
        $.ajax({
            url: url,
            cache: false,
            type: type != 'GET' ? 'POST' : 'GET',
            data: data,
            timeout: 5000,
            error: function (result) {
                var message = '请求失败！';
                var redirect = '';
                if (result.responseJSON.errors) {
                    for (var key in result.responseJSON.errors) {
                        message = result.responseJSON.errors[key][0];
                        break;
                    }
                } else if (result.responseJSON.message) {
                    message = result.responseJSON.message;
                }
                layer.msg(message, {
                    offset: '150px',
                    shade: [0.2, '#666'],
                    shadeClose: true,
                    icon: 2,
                    time: 2000
                });
                setTimeout(function () {
                    ele.prop('disabled', false);
                }, 2000);
                if ($('.captcha-img').length > 0) {
                    $('.captcha-img img').click();
                }
                if (callback && typeof eval(callback) == 'function') {
                    eval(callback)(data, result, ele);
                }
                return false;
            },
            success: function (result) {
                // console.log(result);
                if (result.status == 'success') {
                    if (callback && typeof eval(callback) == 'function') {
                        eval(callback)(data, result, ele);
                    } else {
                        layer.msg(
                            result.message,
                            {
                                offset: '150px',
                                shade: [0.2, '#666'],
                                shadeClose: true,
                                icon: 1,
                                time: 2000
                            },
                            function () {
                                /*
                                 * layer 弹窗属性判断
                                 * @attr layer-close 是否关闭弹窗
                                 * @attr parent-notreload 是否需要刷新父页面 默认刷新
                                 */
                                if (ele.attr('layer-close') === 'true') {
                                    setTimeout(function () {
                                        parent.layer.close(parent.layer.getFrameIndex(window.name));
                                    }, 500);
                                    if (ele.attr('parent-notreload') !== 'true') {
                                        parent.location.reload();
                                    }
                                } else {
                                    if (result.redirect) {
                                        location.href = result.redirect;
                                    } else {
                                        location.reload();
                                    }
                                }
                            }
                        );
                    }
                    return false;
                } else {
                    layer.msg(result.message, {
                        offset: '150px',
                        shade: [0.2, '#666'],
                        shadeClose: true,
                        icon: 2,
                        time: 2000
                    });
                    setTimeout(function () {
                        ele.prop('disabled', false);
                    }, 2000);
                    if ($('.captcha-img').length > 0) {
                        $('.captcha-img img').click();
                    }
                    if (callback && typeof eval(callback) == 'function') {
                        eval(callback)(data, result, ele);
                    }
                    if (result.redirect) {
                        location.href = result.redirect;
                    }
                    return false;
                }
            }
        });
        return false;
    };

    $('body').on('click', '.ajax-get', function (e) {
        $.doAjax(this, 'GET');
        return false;
    });
    $('body').on('click', '.ajax-post', function (e) {
        $.doAjax(this, 'POST');
        return false;
    });
    $('body').on('click', '.ajax-put', function (e) {
        $.doAjax(this, 'PUT');
        return false;
    });
    $('body').on('click', '.ajax-patch', function (e) {
        $.doAjax(this, 'PATCH');
        return false;
    });
    $('body').on('click', '.ajax-delete', function (e) {
        $.doAjax(this, 'DELETE');
        return false;
    });

    /*-------------------------------------------------------------------------------------
     *               prompt简易弹窗表单
     *-----------------------------------------------------------------------------------*/
    $('body').on('click', '.prompt', function (e) {
        var that = this;
        var prompt_title = $(this).attr('prompt-form-title')
            ? $(this).attr('prompt-form-title')
            : '请输入内容';
        var form_type = $(this).attr('prompt-form-type')
            ? $(this).attr('prompt-form-type')
            : 0;
        var width = $(this).attr('prompt-width') ? $(this).attr('prompt-width') : '400px';
        var height = $(this).attr('prompt-height') ? $(this).attr('prompt-height') : '200px';
        layer.prompt(
            {
                offset: '120px',
                move: false,
                title: prompt_title,
                formType: form_type, //prompt风格，支持0-2
                area: [width, height],
                value: $(this).attr('prompt-default-value'),
            },
            function (newvalue) {
                var data_key = $(that).attr('prompt-data-key');
                var post_data = {};
                post_data[data_key] = newvalue;
                post_data['_token'] = $('input[name=_token]').val() ? $('input[name=_token]').val() : $('meta[name=csrf-token]').attr('content')
                console.log(post_data);
                $.ajaxSend($(that), 'POST', $(that).attr('prompt-target'), post_data, '');
                return false;
            }
        );
    });

    /*-------------------------------------------------------------------------------------
     *               菜单高亮
     *-----------------------------------------------------------------------------------*/
    var active_menu = 'menu-' + (highlight_menu == '' ? 'index' : highlight_menu);

    $('#' + active_menu).find('a').first().addClass('active');
    if ($('#' + active_menu).parent().parent().hasClass('has-treeview')) {
        $('#' + active_menu).parent().parent().addClass('menu-open');
        $('#' + active_menu).parent().parent().find('a').first().addClass('active');
    }
    if ($('#' + active_menu).parent().parent().parent().parent().hasClass('has-treeview')) {
        $('#' + active_menu).parent().parent().parent().parent().addClass('menu-open');
        $('#' + active_menu).parent().parent().parent().parent().find('a').first().addClass('active');
    }

    var active_menu = 'menu-' + (highlight_menu == '' ? 'index' : highlight_menu);

    $('#' + active_menu).find('a').first().addClass('active');
    if ($('#' + active_menu).parent().parent().hasClass('has-treeview')) {
        $('#' + active_menu).parent().parent().addClass('menu-open');
        $('#' + active_menu).parent().parent().find('a').first().addClass('active');
    }
    if ($('#' + active_menu).parent().parent().parent().parent().hasClass('has-treeview')) {
        $('#' + active_menu).parent().parent().parent().parent().addClass('menu-open');
        $('#' + active_menu).parent().parent().parent().parent().find('a').first().addClass('active');
    }


    /*-------------------------------------------------------------------------------------
     *               iCheck
     *-----------------------------------------------------------------------------------*/
    $('input').iCheck({
        checkboxClass: 'icheckbox_square-blue',
        radioClass: 'iradio_square-blue',
        increaseArea: '20%' // optional
    })

    /*-------------------------------------------------------------------------------------
     *               layer弹窗iframe
     *-----------------------------------------------------------------------------------*/
    $('.layer-iframe').on('click', function () {
        var _this = this;

        var confirm_title = $(this).attr('confirm_title')
            ? $(this).attr('confirm_title')
            : '确定要执行该操作吗？';

        if ($(this).attr('confirm')) {

            layer.confirm(confirm_title, {
                time: 0, //不自动关闭
                title: false,
                btn: ['确定', '取消'],
                icon: 3,
                offset: '150px',
                shade: [0.2, '#666'],
                yes: function (index) {
                    layer.close(index);
                    $(this).prop('disabled', true);
                    openIframe.call(_this);
                    return false;
                },
                cancel: function (index) {
                    layer.close(index);
                    return false;
                }
            });

        } else {
            openIframe.call(_this);
        }

        function openIframe() {
            var width = $(this).attr('layer-width') ? $(this).attr('layer-width') : '800px';
            var height = $(this).attr('layer-height') ? $(this).attr('layer-height') : '600px';
            var close_confirm = this.hasAttribute('layer-close-confirm') ? ($(this).attr('layer-close-confirm') ? $(this).attr('layer-close-confirm') : '确定关闭吗？') : false;
            layer.open({
                type: 2,
                title: $(this).attr('layer-title'),
                area: [width, height],
                content: $(this).attr('layer-url'),
                cancel: function (index, layero) {
                    if (close_confirm) {
                        if (confirm(close_confirm)) {
                            layer.close(index)
                        }
                        return false;
                    }

                }
            });
        }

    });

    $('.layer-iframe-close').on('click', function () {
        parent.layer.close(parent.layer.getFrameIndex(window.name));
    });


});
